<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<!-- 引入layui的样式-->
<link rel="stylesheet" href="/static/layui/css/layui.css" media="all">
<body>
<form class="layui-form"> <!-- 提示：如果你不想用form，你可以换成div等任何一个普通元素 -->
    <div class="layui-form-item">
        <label class="layui-form-label">账户</label>
        <div class="layui-input-block">
            <input type="text" name="userName" lay-verify="username" placeholder="请输入" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">密码</label>
        <div class="layui-input-block">
            <input type="password" name="password" lay-verify="password" placeholder="请输入密码" autocomplete="off" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">验证码</label>
        <div class="layui-input-block">
            <input type="text" name="code" lay-verify="required" lay-reqtext="验证码不能为空！" placeholder="请输入验证码" autocomplete="off" class="layui-input">
        </div>
        <img src="http://localhost:8080/captcha" style="width:85px" id="cap"/><br>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button type="submit" class="layui-btn" lay-submit="" lay-filter="demo1">登录</button>
        </div>
    </div>
    <!-- 更多表单结构排版请移步文档左侧【页面元素-表单】一项阅览 -->
</form>
<!-- layui的js引入-->
<script src="/static/layui/layui.js"></script>
<script src="/static/js/jquery-3.3.1.js"></script>

<script>
    layui.use('form', function(){
        var form = layui.form;

        //设置验证规则
        form.verify({
            username: function(value){
                if(value.length < 2){
                    return '用户名至少得2个字符啊';
                }
            }
            ,password: [
                /^[\S]{2,6}$/
                ,'密码必须2到6位，且不能出现空格'
            ]
        });



        //form表单提交
        //监听提交
        form.on('submit(demo1)', function(data){
//            layer.alert(JSON.stringify(data.field), {
//                title: '最终的提交信息'
//            })
            //提交到服务器
            $.ajax({
                url:'/user/login',
                type:'post',
                contentType:'application/json',
                data:JSON.stringify(data.field),
                success:function(res){
                    layer.alert(res.message),{
                        title:'登录信息'
                    }
                    if(res.code==200){
                        //跳转页面
                        window.location.href='/page/home.html';
                    }

                }
            })
            return false;
        });
    });
</script>


<script>
    $(function(){
        $("#cap").click(function(){
            //刷新验证码
            path = $(this).attr("src")+"?"+new Date().getTime();
            $(this).attr("src",path);
        });
    });
</script>

</body>
</html>